package com.icedata.sika.core

import com.icedata.sika.bridge.SikaEvent
import com.icedata.sika.core.PreProcessor.Result
import com.icedata.sika.util.read
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import okhttp3.internal.notify
import okhttp3.internal.notifyAll


/**
 * 预处理链，用于挂载预处理器
 * @param sika 所属的sika对象
 */
class PreProcessorBus(sika: Sika) : ProcessorBus<PreProcessor, SikaEvent, Result>(sika) {

    override fun broadcast(data: SikaEvent) {
        lock.read {
            for (p in processors) {
                when (p.execute(data, sika)) {
                    Result.ADOPT -> GlobalScope.async { sika.parseMessageChannel.send(data) }
                    Result.BLOCK -> break
                    Result.IGNORE -> continue
                }
            }
            synchronized(lock) {
                lock.notifyAll()
            }
        }
    }
}